<template>
  <div class="bluetooth-control">
    <div class="status-card">
      <div class="status-icon" :class="{ connected: isConnected }">
        <i class="fas fa-bluetooth"></i>
      </div>
      <div class="status-text">
        {{ statusText }}
      </div>
    </div>

    <div class="control-panel">
      <button 
        class="connect-btn"
        :class="{ disconnect: isConnected }"
        @click="handleConnectionClick"
        :disabled="isLoading"
      >
        {{ isConnected ? '断开连接' : '连接设备' }}
      </button>

      <div class="recording-controls" v-if="isConnected">
        <button 
          class="record-btn"
          :class="{ recording: isRecording }"
          @click="handleRecordingClick"
          :disabled="isLoading"
        >
          {{ isRecording ? '停止录制' : '开始录制' }}
        </button>
        
        <div class="recording-timer" v-if="isRecording">
          录制时间: {{ recordingTime }}
        </div>
      </div>
    </div>

    <div class="device-info" v-if="isConnected">
      <h3>设备信息</h3>
      <p>名称: {{ deviceName }}</p>
      <p>服务 UUID: {{ shortUUID }}</p>
      <p>状态: {{ statusText }}</p>
    </div>

    <div class="video-list" v-if="videoList.length > 0">
      <h3>录制视频列表</h3>
      <ul>
        <li v-for="(video, index) in videoList" :key="index">
          {{ video.name }}
          <span class="video-time">{{ video.time }}</span>
        </li>
      </ul>
    </div>

    <div class="notification-area" v-if="lastVideoName">
      <p>最新视频: {{ lastVideoName }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted, onMounted } from 'vue'
import BluetoothService from '../services/BluetoothService'

// 状态变量
const isConnected = ref(false)
const isLoading = ref(false)
const isRecording = ref(false)
const deviceName = ref('')
const statusText = ref('未连接')
const lastVideoName = ref('')
const recordingTime = ref('00:00')
const recordingStartTime = ref(null)
const videoList = ref([])
let timer = null

// 获取短 UUID
const shortUUID = BluetoothService.SERVICE_UUID.substring(4, 8)

// 更新录制时间
function updateRecordingTime() {
  if (!recordingStartTime.value) return
  
  const diff = Date.now() - recordingStartTime.value
  const minutes = Math.floor(diff / 60000)
  const seconds = Math.floor((diff % 60000) / 1000)
  recordingTime.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 处理连接/断开按钮点击
async function handleConnectionClick() {
  if (isLoading.value) return

  try {
    isLoading.value = true
    
    if (!isConnected.value) {
      // 连接设备
      BluetoothService.checkAvailability()
      await BluetoothService.connect()
      isConnected.value = true
      deviceName.value = BluetoothService.device.name
      statusText.value = '已连接'
    } else {
      // 断开连接
      await BluetoothService.disconnect()
      isConnected.value = false
      deviceName.value = ''
      statusText.value = '未连接'
      isRecording.value = false
    }
  } catch (error) {
    console.error(error)
    statusText.value = '连接失败: ' + error.message
  } finally {
    isLoading.value = false
  }
}

// 处理录制按钮点击
async function handleRecordingClick() {
  if (isLoading.value || !isConnected.value) return

  try {
    isLoading.value = true
    
    if (!isRecording.value) {
      // 开始录制
      await BluetoothService.startRecording()
      isRecording.value = true
      statusText.value = '正在录制'
      recordingStartTime.value = Date.now()
      
      // 启动定时器更新录制时间
      timer = setInterval(updateRecordingTime, 1000)
    } else {
      // 停止录制
      await BluetoothService.stopRecording()
      isRecording.value = false
      statusText.value = '已连接'
      recordingStartTime.value = null
      
      // 停止定时器
      if (timer) {
        clearInterval(timer)
        timer = null
      }
    }
  } catch (error) {
    console.error(error)
    statusText.value = '操作失败: ' + error.message
  } finally {
    isLoading.value = false
  }
}

// 监听通知，处理视频名称
function handleNotification(event) {
  const decoder = new TextDecoder()
  const value = decoder.decode(event.target.value)
  
  if (value.startsWith('VIDEO_NAME:')) {
    const videoName = value.substring(11)
    lastVideoName.value = videoName
    
    // 添加到视频列表
    videoList.value.unshift({
      name: videoName,
      time: new Date().toLocaleTimeString()
    })
  }
}

// 设置通知回调
onMounted(() => {
  BluetoothService.setNotificationCallback(handleNotification)
})

// 组件销毁时清理
onUnmounted(async () => {
  if (timer) {
    clearInterval(timer)
  }
  if (isConnected.value) {
    await BluetoothService.disconnect()
  }
})
</script>

<style scoped>
.bluetooth-control {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.status-card {
  background: #f5f5f5;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
}

.status-icon {
  font-size: 30px;
  color: #999;
  margin-bottom: 10px;
}

.status-icon.connected {
  color: #007AFF;
}

.control-panel {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

button {
  padding: 12px 24px;
  border-radius: 8px;
  border: none;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.connect-btn {
  background: #007AFF;
  color: white;
}

.connect-btn.disconnect {
  background: #FF3B30;
}

.record-btn {
  background: #34C759;
  color: white;
}

.record-btn.recording {
  background: #FF3B30;
}

.device-info {
  background: #f5f5f5;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
}

.device-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.notification-area {
  background: #f5f5f5;
  border-radius: 12px;
  padding: 20px;
}

.recording-timer {
  text-align: center;
  margin-top: 10px;
  font-size: 1.2em;
  color: #FF3B30;
}

.video-list {
  background: #f5f5f5;
  border-radius: 12px;
  padding: 20px;
  margin-top: 20px;
}

.video-list h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.video-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.video-list li {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-list li:last-child {
  border-bottom: none;
}

.video-time {
  color: #666;
  font-size: 0.9em;
}
</style> 